// @/hooks/useCrud.ts

import { ref } from 'vue'
import { message } from 'ant-design-vue'

export interface Pagination {
  current: number
  pageSize: number
  total: number,
  showTotal: Function,
  showSizeChanger: Boolean,
  pageSizeOptions: Array<String>
}

export interface CrudApi<T> {
  getList: (params: any) => Promise<{ page: { list: T[]; currPage: number; pageSize: number; totalCount: number } }>
  create?: (data: T) => Promise<any>
  update?: (data: T) => Promise<any>
  delete?: (ids: (number | string)[]) => Promise<any>
}

export const crud = <T>(api: CrudApi<T>, initSearchForm: Record<string, any> = {}) => {
  // 数据列表
  const dataSource = ref<T[]>([])
  // 分页信息
  const pagination = ref<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
    pageSizeOptions: ['10', '50', '100', '500','1000'],
    showSizeChanger: true,
    showTotal: (total: any, range: any) => `${range[0]}-${range[1]} 共 ${total} 条`,
  })
  // 搜索表单数据
  const searchForm = ref<Record<string, any>>(initSearchForm)
  // 当前选中行ID数组
  const selectedRowKeys = ref<(number | string)[]>([])
  // 是否显示弹窗
  const modalVisible = ref(false)
  // 是否是编辑模式
  const isEditMode = ref(false)
  // 当前表单数据
  const formData = ref<Partial<T>>({})
  // 加载状态
  const loading = ref(false)

  // 加载数据
  const loadData = async (params = { currPage: 1, pageSize: 10 }) => {
    try {
      loading.value = true
      const queryParams = {
        page: params.currPage || 1,
        pageSize: params.pageSize || pagination.value.pageSize,
        ...searchForm.value,
      }

      const response = await api.getList(queryParams)
      const { page } = response

      dataSource.value = page.list
      pagination.value = {
        current: page.currPage,
        pageSize: page.pageSize,
        total: page.totalCount,
        pageSizeOptions: ['10', '50', '100', '500','1000'],
        showSizeChanger: true,
        showTotal: (total: any, range: any) => `${range[0]}-${range[1]} 共 ${total} 条`,
      }
    } catch (error) {
      console.error('获取数据失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 分页变化
  const handleTableChange = (newPagination: Pagination) => {
    loadData({
      currPage: newPagination.current,
      pageSize: newPagination.pageSize,
    })
  }

  // 搜索
  const handleSearch = () => {
    loadData({ currPage: 1, pageSize: pagination.value.pageSize })
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.value = {}
    handleSearch()
  }

  // 删除选中项
  const deleteSelected = () => {
    if (!api.delete) {
      message.warning('未配置删除接口')
      return
    }
    if (selectedRowKeys.value.length === 0) {
      message.warning('请至少选择一项')
      return
    }

    api.delete(selectedRowKeys.value as (number | string)[]).then(() => {
      message.success('操作成功')
      loadData()
    }).catch((err) => {
      console.error('删除失败:', err)
      message.error('删除失败')
    })
  }

  // 打开新增弹窗
  const openAddModal = () => {
    isEditMode.value = false
    formData.value = {}
    modalVisible.value = true
  }

  // 打开编辑弹窗
  const openEditModal = (record: T) => {
    isEditMode.value = true
    formData.value = { ...record }
    modalVisible.value = true
  }

  // 提交表单
  const handleSubmit = async () => {
    try {
      if (isEditMode.value) {
        if (!api.update) {
          message.warning('未配置更新接口')
          return
        }
        await api.update(formData.value as T)
      } else {
        if (!api.create) {
          message.warning('未配置创建接口')
          return
        }
        await api.create(formData.value as T)
      }

      message.success('操作成功')
      modalVisible.value = false
      await loadData()
    } catch (error) {
      console.error('提交失败:', error)
      message.error('提交失败')
    }
  }

  // 关闭弹窗
  const handleCancel = () => {
    modalVisible.value = false
  }

  // 选中行变化
  const onSelectChange = (selectedRowKeysValue: (number | string)[], _selectedRows: T[]) => {
    selectedRowKeys.value = selectedRowKeysValue
  }

  const rowSelection = {
    onChange: onSelectChange,
  }

  // 初始化加载数据
  const initLoad = () => {
    loadData()
  }

  return {
    dataSource,
    pagination,
    searchForm,
    selectedRowKeys,
    modalVisible,
    isEditMode,
    formData,
    loading,

    loadData,
    handleTableChange,
    handleSearch,
    resetSearch,
    deleteSelected,
    openAddModal,
    openEditModal,
    handleSubmit,
    handleCancel,
    rowSelection,

    initLoad,
  }
}
